<?php
declare (strict_types=1);

namespace app\admin\listener;

use app\admin\model\auth\AdminLog;

use app\admin\library\Auth;

class Log
{
    /**
     * 事件监听处理
     *
     * @return mixed
     */
    public function handle($event)
    {
        //
        //只记录POST请求的日志
        if (request()->method() != 'GET') {
            $this->record();
        }
    }

    /**
     * 记录日志
     */
    public function record()
    {
        $auth = Auth::instance();

        $admin_id = $auth->isLogin() ? $auth->id : 0;
        $username = $auth->isLogin() ? $auth->username : lang('Unknown');

        $controllername = strtolower(request()->controller());
        $actionname = strtolower(request()->action());
        $path = str_replace('.', ':', $controllername) . ':' . $actionname;

        $content = request()->param('', [], 'trim,strip_tags,htmlspecialchars');

        $title = [];
        $breadcrumb = $auth->getBreadcrumb($path);
        foreach ($breadcrumb as $k => $v) {
            $title[] = $v['title'];
        }
        $title = implode(' / ', $title) ?: lang($actionname);

        AdminLog::create([
            'admin_id' => $admin_id,
            'username' => $username,
            'title' => $title,
            'content' => json_encode($content, JSON_UNESCAPED_UNICODE),
            'url' => request()->url(),
            'ip' => request()->ip(),
            'method' => request()->method(),
            'user_agent' => request()->header('user-agent'),
        ]);
    }
}
